package com.rush.yuaiagent.agent.model;

import com.itextpdf.styledxmlparser.jsoup.internal.StringUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 处理工具调用的基础代理类，具体实现了think和act方法，可以用作创建实例的父类
 */
@Slf4j
@Data
public abstract class BaseAgent {
    //核心属性
    private String name;
    //提示词
    private String systemPrompt;
    private String nextPrompt;
    //状态
    private AgentState state = AgentState.IDLE;
    //执行控制
    private int maxSteps = 10;
    private int currentStep = 0;
    //LLM
    private ChatClient chatClient;
    //Memory（自主维护上下文）
    List<Message> messageList = new ArrayList<Message>();

    public String run(String prompt) {
        if (this.state != AgentState.IDLE){
            throw new RuntimeException("Cannot run agent from state: " + this.state);
        }
        if (StringUtil.isBlank(prompt)){
            throw new RuntimeException("Cannot run agent with empty user prompt");
        }
        //更改状态
        this.state = AgentState.RUNNING;
        //记录消息上下文
        messageList.add(new UserMessage(prompt));
        //保存结果信息
        try {
            List<String> results = new ArrayList<>();
            for (int i = 0; i < maxSteps && state != AgentState.FINISHED; i++) {
                int stepNumber = i + 1;
                currentStep = stepNumber;
                log.info("Executing step " + stepNumber + "/" + maxSteps);
                //单步执行
                String stepResult = step();
                String result = "Step " + stepNumber + ": " + stepResult;
                results.add(result);
            }
            // 检查是否超出步骤限制
            if (currentStep >= maxSteps) {
                state = AgentState.FINISHED;
                results.add("Terminated: Reached max steps (" + maxSteps + ")");
            }
            return String.join("\n", results);
        } catch (Exception e) {
            state = AgentState.ERROR;
            log.error("Error executing agent", e);
            return "执行错误" + e.getMessage();
        } finally {
            //清理资源
            this.cleanup();
        }
    };

    /**
     * 运行代理（流式输出）
     *
     * @param userPrompt 用户提示词
     * @return SseEmitter实例
     */
    public SseEmitter runStream(String userPrompt) {
        // 创建SseEmitter，设置较长的超时时间
        SseEmitter emitter = new SseEmitter(300000L); // 5分钟超时

        // 使用线程异步处理，避免阻塞主线程
        CompletableFuture.runAsync(() -> {
            try {
                if (this.state != AgentState.IDLE) {
                    emitter.send("错误：无法从状态运行代理: " + this.state);
                    emitter.complete();
                    return;
                }
                if (StringUtil.isBlank(userPrompt)) {
                    emitter.send("错误：不能使用空提示词运行代理");
                    emitter.complete();
                    return;
                }

                // 更改状态
                state = AgentState.RUNNING;
                // 记录消息上下文
                messageList.add(new UserMessage(userPrompt));

                try {
                    for (int i = 0; i < maxSteps && state != AgentState.FINISHED; i++) {
                        int stepNumber = i + 1;
                        currentStep = stepNumber;
                        log.info("Executing step " + stepNumber + "/" + maxSteps);

                        // 发送步骤开始信息
                        emitter.send("rush-step:Step " + stepNumber + "/" + maxSteps + " - 开始执行");

                        // 执行思考阶段 (对于ReActAgent)
                        if (this instanceof ReActAgent) {
                            ReActAgent reactAgent = (ReActAgent) this;
                            try {
                                emitter.send("rush-think:正在分析问题和选择工具...");
                                boolean shouldAct = reactAgent.think();
                                
                                // 如果是ToolCallAgent，获取详细的思考信息
                                if (this instanceof ToolCallAgent) {
                                    ToolCallAgent toolCallAgent = (ToolCallAgent) this;
                                    String thinkingDetail = toolCallAgent.getLastThinkingDetail();
                                    if (thinkingDetail != null && !thinkingDetail.trim().isEmpty()) {
                                        emitter.send("rush-think:" + thinkingDetail);
                                    }
                                }
                                
                                if (!shouldAct) {
                                    emitter.send("rush-think:✅ 思考完成 - 无需调用工具");
                                    emitter.send("rush-act:⏭️ 跳过行动阶段");
                                    continue;
                                } else {
                                    emitter.send("rush-think:✅ 思考完成 - 准备执行工具");
                                }
                                
                                // 执行行动阶段
                                emitter.send("rush-act:🚀 开始执行选定的工具...");
                                String actionResult = reactAgent.act();
                                
                                // 如果是ToolCallAgent，获取详细的行动信息
                                if (this instanceof ToolCallAgent) {
                                    ToolCallAgent toolCallAgent = (ToolCallAgent) this;
                                    String actionDetail = toolCallAgent.getLastActionDetail();
                                    if (actionDetail != null && !actionDetail.trim().isEmpty()) {
                                        emitter.send("rush-act:" + actionDetail);
                                    }
                                } else {
                                    emitter.send("rush-act:" + actionResult);
                                }
                                
                            } catch (Exception e) {
                                emitter.send("rush-think:❌ 思考过程出现错误: " + e.getMessage());
                                emitter.send("rush-act:⏹️ 由于思考错误，跳过行动阶段");
                            }
                        } else {
                            // 对于非ReActAgent，使用原有的step方法
                            String stepResult = step();
                            emitter.send("rush-step:" + stepResult);
                        }
                    }
                    
                    // 检查是否超出步骤限制
                    if (currentStep >= maxSteps) {
                        state = AgentState.FINISHED;
                        emitter.send("rush-step:执行结束 - 达到最大步骤 (" + maxSteps + ")");
                    } else if (state == AgentState.FINISHED) {
                        emitter.send("rush-step:执行结束 - 任务完成");
                    }
                    
                    // 正常完成
                    emitter.complete();
                } catch (Exception e) {
                    state = AgentState.ERROR;
                    log.error("执行智能体失败", e);
                    try {
                        emitter.send("rush-step:执行错误: " + e.getMessage());
                        emitter.complete();
                    } catch (Exception ex) {
                        emitter.completeWithError(ex);
                    }
                } finally {
                    // 清理资源
                    this.cleanup();
                }
            } catch (Exception e) {
                emitter.completeWithError(e);
            }
        });

        // 设置超时和完成回调
        emitter.onTimeout(() -> {
            this.state = AgentState.ERROR;
            this.cleanup();
            log.warn("SSE connection timed out");
        });

        emitter.onCompletion(() -> {
            if (this.state == AgentState.RUNNING) {
                this.state = AgentState.FINISHED;
            }
            this.cleanup();
            log.info("SSE connection completed");
        });

        return emitter;
    }

    public abstract String step();
    protected void cleanup(){
        //子类重写该方法逻辑
    }
}
